/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package models;

import com.sun.image.codec.jpeg.JPEGDecodeParam;
import java.util.*;
import javax.persistence.*;
import play.data.validation.MaxSize;
import play.data.validation.Required;
import play.db.jpa.*;
/**
 *
 * @author alex
 */
    @Entity
public class Post extends Model{
    @Required
    public String title;
    
    @Required
    public Date postedAt;
    
    @Lob
    @Required
    @MaxSize(100000)
    public String content;
    
    @ManyToOne
    @Required
    public User author;

    @OneToMany(mappedBy = "post", cascade = CascadeType.ALL)
    public List<Comment> comments;
    
    @ManyToMany(cascade = CascadeType.PERSIST)
    public Set<Tag> tags;
    
    public Post(String title, String content, User author) {
        this.title = title;
        this.postedAt = new Date();
        this.content = content;
        this.author = author;
        this.comments = new ArrayList<Comment>();
        this.tags = new TreeSet<Tag>();
    }
    
    public Post addComment (String author, String content) {
    Comment newComment = new Comment(author, content, this).save();
    this.comments.add(newComment);
    this.save();
    return this;
    //post-author-content
    
    }
    
    public Post previous(){
        return Post.find("postedAt < ? order by postedAt desc", postedAt).first();
    }
    
    public Post next(){
        return Post.find("postedAt > ? order by postedAt asc", postedAt).first();
    }
    
    public Post tagItWith(String name){
    tags.add(Tag.findOrCreateByName(name));
    return this;
    }
    
    public static List<Post> findTaggedWith(String tag){
        return Post.find("select distinct p from Post p join p.tags as t where t.name =?", tag).fetch();
    
    }
    
    public static List<Post> findTaggedWith(String... tags) {
    return Post.find(
            "select distinct p from Post p join p.tags as t where t.name in (:tags) group by p.id, p.author, p.title, p.content,p.postedAt having count(t.id) = :size"
    ).bind("tags", tags).bind("size", tags.length).fetch();
}
    
    public String toString(){
    return title;
    }
    
}
